package com.sys.dispatch;


import org.apache.log4j.Logger;

import com.sys.db.dao.DefFlowDao;
import com.sys.db.dao.LogFlowDao;
import com.sys.db.util.ExtendDate;
import com.sys.db.util.GetBeanUtil;
import com.sys.db.util.ThreadArray;
import com.sys.pojo.DefFlow;
import com.sys.pojo.LogFlow;

public class FlowThread extends Thread{
	protected static Logger log = Logger.getLogger(FlowThread.class);
	private DefFlow ob;
	public FlowThread(DefFlow obj){
		this.ob=obj;
	}
	public void run(){
		log.info("----------------------------自动调度线程开始-------------------------------");
		DefFlowDao defDao=(DefFlowDao) GetBeanUtil.getDao("defFlowDaoImpl");//作业流dao
		LogFlowDao logFlowDao=(LogFlowDao) GetBeanUtil.getDao("logFlowDaoImpl");//作业流日志dao
		DispatchUtil disUtil=new DispatchUtil();
		boolean stop=false;//作业流停止标志
		LogFlow ll=new LogFlow();//记录作业流日志
		String message="";
		int flowlogId=-1;
		boolean success=true;
		while(true){//设置该作业流是否要执行
			try{
				boolean flag = false;//挂起标志
				String depend=ob.getDependId();//依赖作业流
				log.info("作业流["+ob.getFlowName()+"]状态"+ob.getStatus());
				if("1".equals(ob.getStatus())){//判断本作业流是否正在运行
					message="作业流["+ob.getFlowName()+"]正在运行";
					throw new ExpServiceException("作业流["+ob.getFlowId()+"-"+ob.getFlowName()+"]正在运行");
				}else if(depend!=null&&!"".equals(depend)){
					String[] dIds=depend.split(",");
					for(int i=0; i<dIds.length; i++){
						DefFlow def=defDao.findById(new Integer(dIds[i]));//根据依赖的作业流ID查找作业流
						if(def!=null){
							if("1".equals(def.getStatus())){//如果是正在运行状态
								log.info("作业流["+ob.getFlowName()+"]依赖的作业流["+def.getFlowName()+"]正在运行");
								flag=true;
								break;
							}else{
								if(disUtil.validateStatus(def)){
									log.info("依赖的作业流数据没有成功！");
									flag=true;
									break;
//									throw new ExpServiceException("依赖的作业流数据没有成功！");
								}
							}
						}else{
							message="没有该作业流";
							throw new ExpServiceException("没有该作业流");
						}
					}
				}
				if(!flag){
//					判断该作业流包含的作业是否存在其他作业流中，存在且正在运行的，则本作业流等待 
					flag=disUtil.jobFromFlowIsRun(ob);
				}
				if(flag){
					if(ll.getWaitSTime()==null||"".equals(ll.getWaitSTime())){
						ll.setWaitSTime(ExtendDate.getSysDate());//等待开始时间
					}else{
						long waitTime=ExtendDate.getTimeDifferenceMin(ll.getWaitSTime(), ExtendDate.getSysDate());
						log.info("作业流["+ob.getFlowName()+"]已等待"+waitTime+"分钟！");
						if(waitTime>=ob.getMaxWaitTime()){
							throw new ExpServiceException("等待时间超出设定等待时间！");
						}
					}
					if(ll.getFlowId()==null){
						ll.setFlowId(ob.getFlowId());
						ll.setDataDate(disUtil.getDataDate(ob));
						if(flowlogId!=-1){
							logFlowDao.update(ll);
						}else{
							logFlowDao.save(ll);
						}
						flowlogId=ll.getId();
					}
					log.info("作业流["+ob.getFlowName()+"]挂起等待！");
					Thread.sleep(1000*60);
				}else{
					break;
				}
			}catch(ExpServiceException e){
				stop=true;
				ll.setFlowId(ob.getFlowId());
				ll.setDataDate(disUtil.getDataDate(ob));
				ll.setErrTxt(e.getMessage());
				log.info(e.getMessage());
				try {
					if(flowlogId!=-1){
						logFlowDao.update(ll);
					}else{
						logFlowDao.save(ll);
					}
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				flowlogId=ll.getId();
				success=false;
				break;
			}catch(Exception e){
				stop=true;
				ll.setFlowId(ob.getFlowId());
				ll.setDataDate(disUtil.getDataDate(ob));
				ll.setErrTxt("系统异常");
				try {
					if(flowlogId!=-1){
						logFlowDao.update(ll);
					}else{
						logFlowDao.save(ll);
					}
				} catch (Exception e1) {
					e1.printStackTrace();
					log.info(e1.getMessage());
				}
				log.info(e.getMessage());
				flowlogId=ll.getId();
				success=false;
				break;
			}
		}
		try{
			while(!stop){//如果作业流不需要停止，则执行作业
				//更新作业流状态，并写日志表
				log.info("作业流["+ob.getFlowName()+"]开始执行！");
				ob.setStatus("1");
				defDao.update(ob);//更新作业流状态
				if(ll.getWaitSTime()!=null&&!"".equals(ll.getWaitSTime())){
					ll.setWaitETime(ExtendDate.getSysDate());
				}
				ll.setFlowId(ob.getFlowId());
				ll.setDataDate(disUtil.getDataDate(ob));
				ll.setRunSTime(ExtendDate.getSysDate());
				if(flowlogId!=-1){
					logFlowDao.update(ll);//写日志表
				}else{
					logFlowDao.save(ll);
				}
				disUtil.exeJobOfFlow(ob);//执行作业流
				stop=true;//作业执行完 结束线程
				ob.setStatus("0");
				ob.setAvgRun((int)disUtil.getAvgTimes(ob, ll.getRunSTime()));
				ob.setRuntimes(ob.getRuntimes()+1);
				defDao.update(ob);//更新作业流状态
				ll.setRunETime(ExtendDate.getSysDate());
				ll.setStatus("0");
				logFlowDao.update(ll);
				log.info("作业流["+ob.getFlowName()+"]运行结束！");
			}
		}catch(ExpServiceException e){
			success=false;
			ll.setErrTxt(e.getMessage());
			log.error(e.getMessage());
		}catch(Exception e){
			success=false;
			ll.setErrTxt("系统异常");
			log.error(e.getMessage());
		}
		finally{
			if(success){
				ll.setStatus("0");
				ob.setStatus("0");
			}else{
				ll.setStatus("2");
				ob.setStatus("2");
			}
			ll.setRunETime(ExtendDate.getSysDate());
			try {
				if(flowlogId!=-1){
					logFlowDao.update(ll);
				}else{
					logFlowDao.save(ll);
				}
				defDao.update(ob);
			} catch (Exception e) {
				e.printStackTrace();
			}
			log.info("----------------------------自动调度线程结束！-------------------------------");
			ThreadArray.moveThread(ob.getFlowId());
		}
	}
	
	
}
